import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router} from "@angular/router";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {Monitor} from "../monitor";
import {MonitorService} from "../monitor.service";
import {MsgResult} from "../../../../models/msg-result";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgConstants} from "../../../../constants/constants";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {DataDictionaryService} from "../../../../services/dataDictionary.service";
import {FormUtil} from "../../../../util/form-util";

@Component({
  selector: 'app-site-monitor-add',
  templateUrl: './site-monitor-add.component.html'
})
export class SiteMonitorAddComponent implements OnInit {

  monitor : Monitor;

  monitorForm : FormGroup;

  codMonitors ;
  //设备状态
  dicStatusArr: Array<string> = [];
  // 传输方式
  dicTransModeArr: Array<string> = [];
  // 数据算法模式
  dicarithmeticArr: Array<string> = [];



  constructor(
    private router :Router,
    private route :ActivatedRoute,
    private pageSubject : PageSubject,
    private fb : FormBuilder,
    private dialogService :OneDialogService,
    private dataDictionaryService :DataDictionaryService,
    private responseUtil : ResponseUtil,
    private formUtil : FormUtil,
    private monitorService : MonitorService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initMonitorType();
    this.initDataDictionary();
  }

  /**
   * 面包屑
   */
  private pushPage(){
    let path =new Path("运维管理","");
    this.pageSubject.pushPage("设备管理","添加",path);
   }

  /**
   * 构造表单
   */
 private buildForm():void{
    this.monitorForm=this.fb.group({
      'id': [this.monitor.id],
      'snCode': [this.monitor.snCode,[
        Validators.required
      ]],
      'location': [this.monitor.location],
      'parameter': [this.monitor.parameter],
      'status': [this.monitor.status = '1'],
      'monitorCode': [this.monitor.monitorCode = "257",[
        Validators.required,
      ]],
      'mPhone': [this.monitor.mPhone,[
        Validators.maxLength(14),
        Validators.pattern(/(^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$)|(^\d{3,4}-?\d{7,9}$)/)
      ]],
      'remark': [this.monitor.remark,[
        Validators.maxLength(30)
      ]],
      'transMode': [this.monitor.transMode = "1",[
        Validators.maxLength(20)
        ]],
      'arithmeticType': [this.monitor.arithmeticType = "0",[
        Validators.maxLength(1)
        ]]

    });

     this.monitorForm.valueChanges.subscribe(
       data => this.onValueChanged(data)
     );
     this.onValueChanged();
   }

  private onValueChanged(data ?: any) {
    if (!this.monitorForm) {
      return;
    }
    const form = this.monitorForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'snCode': '',
    'monitorCode': '',
    'mPhone': '',
    'remark': '',
    'transMode': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'snCode': {
      'required': '设备编号不能为空',
      'maxlength': '长度不能超过10',
      'pattern': '只能由字母、数字、下划线组成'
    },
    'monitorCode': {
      'required': '设备类型不能为空',
    },
    'mPhone': {
      'maxlength': '长度不能超过14位',
      'pattern': '格式不正确'
    },
    'remark': {
      'maxlength': '长度不能超过30位',
    },
    'transMode': {
      'required': '数据传输方式不能为空',
      'maxlength': '长度不能超过20位',
    },
    'arithmeticType': {
      'required': '数据传输方式不能为空',
      'maxlength': '长度不能超过20位',
    }
  };


  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType(){
    this.monitorService.getMonitor().subscribe(
      result => this.responseUtil.success(result ,this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.codMonitors = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化数据字典数据
   */
   initDataDictionary(){
     this.dataDictionaryService.getChildDicByCode('SBGL').subscribe(
       result => this.responseUtil.success(result ,this.processDictionaryResult),
       message => this.responseUtil.error(message)
     )
   }

  /**
   * 处理查询结果
   * @param result
   */
  private processDictionaryResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dicStatusArr = this.formUtil.filterDictionaryByCode('SBGL_SBZT',result.data);
      this.dicTransModeArr = this.formUtil.filterDictionaryByCode('SBGL_SJCSFS',result.data);
      this.dicarithmeticArr = this.formUtil.filterDictionaryByCode('SBGL_SJSFMS',result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 实现添加
   */
  onSubmit() {
    this.monitor = this.monitorForm.value;
    this.monitorService.siteMonitorAdd(this.monitor).subscribe(
      result => this.responseUtil.success(result, this.processSiteMonitorResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   * 获取添加日志
   * @param result
   */
  private processSiteMonitorResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.successWithCancelBtn("添加成功，是否继续添加？", () => this.initObject(), () => this.cancelSiteMonitorAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 站点添加取消
   */
   cancelSiteMonitorAdd(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }

  private initObject() {
    this.monitor = new Monitor();
    this.buildForm();
  }

}
